#include "server.h"
#include "database.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QByteArray>
#include <QTcpSocket>
#include <QVector>


Server::Server(QObject *parent) :  tcpServer(new QTcpServer(this))
{
    tcpServer=new QTcpServer(this);
    connect(tcpServer,&QTcpServer::newConnection,this,&Server::onNewConnection);
  }

void Server::startServer(){
    if(!tcpServer->listen(QHostAddress::Any,8022)){
        qDebug() << "Unable to start the server:" << tcpServer->errorString();
        return;
    }
    qDebug() << "Server started on port" << tcpServer->serverPort();
}


//当出现一个新的连接时，TcpServer便会触发onNewConnection函数，每有一个新的连接都会触发一次，即都创建一个新对象
void Server::onNewConnection()
{
    qDebug()<<"server onNewConnection connected"<<endl;
    QTcpSocket *clientSocket=tcpServer->nextPendingConnection();
    clients.append(clientSocket);
    connect(clientSocket,&QTcpSocket::readyRead,this,&Server::updateClients);
    connect(clientSocket,&QTcpSocket::disconnected,this,&Server::slotDisconnected);
}

void Server::updateClients(){
    qDebug() << "调用updateClients函数" <<endl;
    QTcpSocket *clientSocket =qobject_cast<QTcpSocket*>(sender());
    if(!clientSocket)
        return;
    int length=clients.size();
    //从客户端读取json数据
    QByteArray jsonData=clientSocket->readAll();
    QString type,a,p,name,message;
    QJsonDocument dataDocument=QJsonDocument::fromJson(jsonData);
    if(!dataDocument.isNull()&&dataDocument.isObject()){
        QJsonObject dataObject=dataDocument.object();
        QJsonObject resultObject;
        qDebug()<<"sendtype="<<dataObject["sendtype"].toString();

        //登陆界面
        if(dataObject["sendtype"].toString()=="login"){
            a=dataObject["selfaccount"].toString();
            p=dataObject["selfpassword"].toString();
            resultObject.insert("returntype","login");
            if(DataBase::getInstance()->Isacc_pawRight(a,p)){
                resultObject.insert("isLogin",true);
                QString name=DataBase::getInstance()->getSelfName(a);
                QString pic=DataBase::getInstance()->getSelfPic_Path(a);
                QString sig=DataBase::getInstance()->getSelfSig(a);
                resultObject.insert("selfaccount",a);
                resultObject.insert("selfname",name);
                resultObject.insert("selfpic_path",pic);
                resultObject.insert("selfsignature",sig);
            }else{
                resultObject.insert("isLogin",false);
            }

            //向指定客户端发送信息
            QJsonDocument resultDocument(resultObject);
            QByteArray  jsonResult=resultDocument.toJson();
            clientSocket->write(jsonResult);
        }
        //注册界面
        else
            if(dataObject["sendtype"].toString()=="register"){
                a=dataObject["selfaccount"].toString();
                p=dataObject["selfpassword"].toString();
                QString n=dataObject["selfname"].toString();
                resultObject.insert("returntype","register");
                if(DataBase::getInstance()->isAccountExit("qq_clients",a)){
                    resultObject.insert("isRegister",false);
                }
                else{
                    DataBase::getInstance()->insertUser(a,p,n);
                    resultObject.insert("isRegister",true);
                    DataBase::getInstance()->create_New_Table(a);    //建立好友表
                }
                QJsonDocument resultDocument(resultObject);
                QByteArray  jsonResult=resultDocument.toJson();
                clientSocket->write(jsonResult);
            }
        //单人聊天界面 用于将每个客户端的信息存到QList<QTcpSocket*> chat中
            else
                if(dataObject["sendtype"].toString()=="chat_start"){
                    clientSocket->setProperty("my_account",dataObject["selfaccount"].toString());
                    clientSocket->setProperty("myfriend_account",dataObject["friaccount"].toString());
                    clientSocket->setProperty("Listname","chat");
                    chat.append(clientSocket);
                }

        //单人聊天消息交互
                else
                    if(dataObject["sendtype"].toString()=="singlechat"){
                        name=dataObject["selfname"].toString();
                        message=dataObject["message"].toString();
                        resultObject.insert("selfaccount",dataObject["selfaccount"].toString());
                        resultObject.insert("returntype","singlechat");
                        resultObject.insert("friname",dataObject["friname"].toString());
                        resultObject.insert("selfname",name);
                        resultObject.insert("message",message);

                        QJsonDocument resultDocument(resultObject);
                        QByteArray  jsonResult=resultDocument.toJson();
                        qDebug()<<"chat 里socket的数量"<<chat.size();
                       int people=0;
                        for(QTcpSocket*cSocket:chat){
                            if((dataObject["selfaccount"].toString()==cSocket->property("my_account").toString()&&
                                dataObject["friaccount"].toString()==cSocket->property("myfriend_account").toString())||
                                    ( dataObject["selfaccount"].toString()==cSocket->property("myfriend_account").toString()&&
                                      dataObject["friaccount"].toString()==cSocket->property("my_account").toString())){
                                cSocket->write(jsonResult);
                                people++;
                            }
                        }
                        qDebug()<<"people="<<people;
                        if(people==1){
                            bool friendonline=false;
                            for(QTcpSocket* socket:onlinepeople){
                                if(socket->property("my_account")==dataObject["friaccount"].toString()){
                                    friendonline=true;
                                    QJsonObject object;
                                    object.insert("returntype","messagereminding");
                                    object.insert("sendpeoplename",name);
                                    object.insert("sendpeopleaccount",dataObject["selfaccount"].toString());
                                    object.insert("receivepeopleaccount", dataObject["friaccount"].toString());
                                    object.insert("message",message);
                                    QJsonDocument document(object);
                                    QByteArray result=document.toJson();
                                    socket->write(result);
                                }
                            }

                        }

                    }
        //查找好友
                    else
                        if(dataObject["sendtype"].toString()=="searchfriend"){
                            resultObject.insert("returntype","searchfriend");
                            QString searchacc=dataObject["searchacc"].toString();
                            if(DataBase::getInstance()->isPeopleExit(searchacc,"qq_clients")){
                                QString searchname=DataBase::getInstance()->getSelfName(searchacc);
                                QString searchpic=DataBase::getInstance()->getSelfPic_Path(searchacc);
                                resultObject.insert("searchresult",true);
                                resultObject.insert("searchname",searchname);
                                resultObject.insert("searchpic",searchpic);
                                resultObject.insert("selfaccount",dataObject["selfacc"].toString());
                            }else
                            {
                                resultObject.insert("searchresult",false);
                            }
                            QJsonDocument resultDocument(resultObject);
                            QByteArray  jsonResult=resultDocument.toJson();
                            clientSocket->write(jsonResult);
                        }
       //修改个人信息
                      else
                            if(dataObject["sendtype"].toString()=="changeinformation"){
                                QString name=dataObject["selfname"].toString();
                                QString account=dataObject["selfaccount"].toString();
                                QString pic=dataObject["selfpic"].toString();
                                QString sig=dataObject["selfsig"].toString();
                                DataBase::getInstance()->changeselfinformation(account,name,pic,sig);
                                resultObject.insert("returntype","changeinformation");
                                resultObject.insert("selfname",name);
                                resultObject.insert("selfpic",pic);
                                resultObject.insert("selfsig",sig);
                                QJsonDocument resultDocument(resultObject);
                                QByteArray  jsonResult=resultDocument.toJson();
                                for(QTcpSocket*socket1:onlinepeople){
                                    if(account==socket1->property("my_account").toString()){

                                        socket1->write(jsonResult);
                                    }

                                }
                            }

        //好友列表
                        else
                            if(dataObject["sendtype"].toString()=="friendlist"){
                                QString selfaccount=dataObject["selfaccount"].toString();
                                QVector<QString> rsl;

                                clientSocket->setProperty("my_account",selfaccount);
                                clientSocket->setProperty("Listname","onlinepeople");
                                onlinepeople.append(clientSocket);

                                DataBase::getInstance()->show_search_rsl(selfaccount,rsl);
                                resultObject.insert("returntype","friendlist");
                                resultObject.insert("size",rsl.size());
                                for (int i=0;i<rsl.size();i++)
                                {
                                    QString a=QString::number(i);
                                    resultObject.insert(a,rsl.at(i));
                                }
                                QJsonDocument resultDocument(resultObject);
                                QByteArray  jsonResult=resultDocument.toJson();
                                clientSocket->write(jsonResult);
                            }
        //添加好友
                            else
                                if(dataObject["sendtype"].toString()=="addfriend"){
                                    resultObject.insert("returntype","addfriend");
                                    qDebug()<<dataObject["selfaccount"].toString()<<endl;
                                    resultObject.insert("sendpeopleacc",dataObject["selfaccount"].toString());
                                    resultObject.insert("receivepeopleacc",dataObject["friendinformation"].toString());
                                    QString selfacc=dataObject["selfaccount"].toString();
                                    QString friacc=dataObject["friendinformation"].toString();
                                    resultObject.insert("people","sender");
                                    QString friname=DataBase::getInstance()->getSelfName(friacc);
                                    QString frinpaw=DataBase::getInstance()->getSelfPassword(friacc);
                                    QString fripic=DataBase::getInstance()->getSelfPic_Path(friacc);
                                    QString frisig=DataBase::getInstance()->getSelfSig(friacc);
                                    QString myname=DataBase::getInstance()->getSelfName(selfacc);
                                    QString mypaw=DataBase::getInstance()->getSelfPassword(selfacc);
                                    QString mypic=DataBase::getInstance()->getSelfPic_Path(selfacc);
                                    QString mysig=DataBase::getInstance()->getSelfSig(selfacc);
                                    DataBase::getInstance()->insertFriend(selfacc,friacc,frinpaw,friname,fripic,frisig);
                                    DataBase::getInstance()->insertFriend(friacc,selfacc,mypaw,myname,mypic,mysig);

                                    resultObject.insert("friacc",friacc);
                                    resultObject.insert("selfpic",mypic);
                                    resultObject.insert("selfname",myname);
                                    resultObject.insert("friname",friname);
                                    resultObject.insert("fripic",fripic);
                                    resultObject.insert("friname",myname);
                                    resultObject.insert("fripic",mypic);
                                    QJsonDocument resultDocument(resultObject);
                                    QByteArray  jsonResult=resultDocument.toJson();
                                    for (QTcpSocket *clientSocket : clients)
                                    {
                                        clientSocket->write(jsonResult);
                                    }
                                }

         //实现群聊的加入
                                else
                                    if(dataObject["sendtype"].toString()=="groupchat_start"){
                                        QString selfname=dataObject["selfname"].toString();
                                        QString selfaccount=dataObject["selfaccount"].toString();
                                        QString entertime=dataObject["entertime"].toString();
                                        resultObject.insert("returntype","groupchat_start");
                                        resultObject.insert("selfname",selfname);
                                        resultObject.insert("entertime",entertime);
                                        clientSocket->setProperty("my_account",selfaccount);
                                        clientSocket->setProperty("Listname","groupChat");
                                        groupChat.append(clientSocket);
                                        QJsonDocument resultDocument(resultObject);
                                        QByteArray  jsonResult=resultDocument.toJson();
                                        for(QTcpSocket*gSocket:groupChat){
                                            gSocket->write(jsonResult);
                                        }
                                    }
        //实现群聊发送信息
                                    else
                                        if(dataObject["sendtype"].toString()=="groupchat"){
                                            QString selfname=dataObject["selfname"].toString();
                                            QString message=dataObject["message"].toString();
                                            QString selfaccount=dataObject["selfaccount"].toString();
                                            resultObject.insert("returntype","groupchat");
                                            resultObject.insert("selfaccount",selfaccount);
                                            resultObject.insert("selfname",selfname);
                                            resultObject.insert("message",message);
                                            QJsonDocument resultDocument(resultObject);
                                            QByteArray  jsonResult=resultDocument.toJson();
                                            for(QTcpSocket*gSocket:groupChat){
                                                gSocket->write(jsonResult);
                                            }
                                        }
    }
}

void Server::slotDisconnected(){
    QTcpSocket *clientSocket=qobject_cast<QTcpSocket*>(sender());
    if(!clientSocket)
        return;
    if(clientSocket->property("Listname").toString()=="chat"){
        chat.removeOne(clientSocket);
        qDebug()<<"删去chat里的一个socket，此时chat.size="<<chat.size();
    }
    else
        if(clientSocket->property("Listname").toString()=="groupChat"){
            groupChat.removeOne(clientSocket);
              qDebug()<<"删去groupChat里的一个socket，此时groupChat.size="<<groupChat.size();
        }
    else
        if(clientSocket->property("Listname").toString()=="onlinepeople"){
            onlinepeople.removeOne(clientSocket);
              qDebug()<<"删去onlinepeople里的一个socket，此时onlnepeo.size="<<onlinepeople.size();
        }
    clients.removeOne(clientSocket);
    clientSocket->deleteLater();
}

void Server::broadcastMessage(const QJsonObject &dataObject){
    QJsonDocument dataDocument(dataObject);
    QByteArray jsonData=dataDocument.toJson();
    for(QTcpSocket*client : clients){
        client->write(jsonData);
    }
}


